<template>
  <el-dialog :visible.sync="openx" width="95%" append-to-body :before-close="close">
    <el-divider content-position="center">{{ title }}</el-divider>
    <el-row :gutter="24">
      <el-col :span="11">
        <el-card shadow="always" class="box-card-left">
          <el-form :inline="true" label-width="100px">
            <div class="area">
              <div class="column">
                <p class="zi1">入库单号:</p>
                <p class="zi2">{{ form.warehousing_id }}</p>
              </div>
              <div class="column column2">
                <p class="zi1">剩余数量:</p>
                <p class="zi2">{{ residue }}</p>
              </div>
            </div>
            <div class="area">
              <div class="column">
                <p class="zi1">商品总数:</p>
                <p class="zi2">{{ u_number }}</p>
              </div>
              <div class="column column2">
                <p class="zi1">箱总数:</p>
                <p class="zi2">{{ u_box_number }}</p>
              </div>
            </div>
            <el-row>
              <el-col :span="24">
                <span style="margin-right: 50px;">批次号:</span>
                <el-input v-model="form.batch_number" style="width: 30%;" />
                <el-button type="primary" plain style="float: right;margin-bottom: 20px;margin-right: 45px;" @click="addList">增加库位</el-button>
              </el-col>
            </el-row>
          </el-form>

          <el-form :inline="true" label-width="80px">
            <el-card v-for="item in list" :key="item.id" class="box-card" style="margin-top: 5px;">
              <div slot="header" class="clearfix">
                <el-row>
                  <el-col :span="5">
                    <el-form-item label="托盘码">
                      <el-input v-model="item.tray_id" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="5">
                    <el-form-item label="总数量">
                      <el-input v-model="item.number" :disabled="true" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="5">
                    <el-form-item label="总箱数">
                      <el-input v-model="item.box_number" :disabled="true" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="5">
                    <el-form-item label="状态">
                      <el-select v-model="item.goods_status" placeholder="请选择">
                        <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.label"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <i class="el-icon-delete" @click="del(item.id)" />
                    <i class="el-icon-circle-plus-outline" @click="add(item.id)" />
                  </el-col>
                </el-row>
              </div>
              <div v-for="it in item.products" :key="it.id" class="text item">
                <el-col :span="6">
                  <el-form-item label="商品">
                    <el-select v-model="it.productInfo[0]" filterable placeholder="请选择" @change="proChange(item.id,it.id,$event)">
                      <el-option
                        v-for="itx in it.selectPro"
                        :key="itx.value"
                        :label="itx.label"
                        :value="itx.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="包装">
                    <el-select v-model="it.productInfo[1]" filterable placeholder="请选择" @change="packingChange(item.id,it.id,it.number,$event)">
                      <el-option
                        v-for="itx in it.selectPacking"
                        :key="itx.value"
                        :label="itx.label"
                        :value="itx.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <!--                <el-col :span="8">-->
                <!--                  <el-form-item v-if="!isLoad" label="商品包装">-->
                <!--                    <el-cascader-->
                <!--                      v-model="it.productInfo"-->
                <!--                      placeholder="请选择商品和包装"-->
                <!--                      :options="selectPro"-->
                <!--                      clearable-->
                <!--                      :props="props"-->
                <!--                      filterable-->
                <!--                    />-->
                <!--                  </el-form-item>-->
                <!--                  <el-form-item v-if="isLoad" label="商品包装">-->
                <!--                    <el-cascader-->
                <!--                      disabled-->
                <!--                      placeholder="数据加载中..."-->
                <!--                      style="width: 100%"-->
                <!--                    />-->
                <!--                  </el-form-item>-->
                <!--                </el-col>-->
                <el-col :span="4">
                  <el-form-item label="数量">
                    <el-input v-model="it.number" @change="changeNum(item.id,it.id,$event)" />
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="箱数">
                    <el-input v-model="it.box_number" :disabled="true" />
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <i class="el-icon-delete" style="margin-top: 35%;" @click="del_son(item.id,it.id)" />
                </el-col>
              </div>
            </el-card>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="13">
        <el-card v-loading="loading" shadow="always" class="box-card-right">
          <el-form ref="form2" label-width="50px">
            <el-form-item label="库位" prop="location">
              <el-cascader
                v-model="location"
                placeholder="请选择库位"
                :options="selectData"
                clearable
                filterable
                style="width: 30%;"
              />
              <el-input v-model="search" placeholder="请输入库位关键词" style="width: 20%;margin-left: 3%;" />
              <el-button icon="el-icon-search" type="primary" plain circle style="margin-left: 15px;" @click="getBox" />
            </el-form-item>
            <el-form-item label="隐藏已占用的库位" label-width="200px">
              <el-checkbox v-model="checked">隐藏</el-checkbox>
            </el-form-item>
            <el-form-item label="" label-width="10px">
              <span v-for="(item,index) in choice" :key="index">{{ item }} / </span>
            </el-form-item>
          </el-form>
          <div style="margin-top: 20px;overflow-y:auto;">
            <el-checkbox-group v-model="choice" size="medium" :max="max">
              <el-checkbox-button v-for="item in box" :key="item.config_id" :label="item.name" class="box" border />
            </el-checkbox-group>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row style="top: 30px;margin-bottom: 30px;text-align:center;">
      <el-col :span="24">
        <el-button type="primary" size="medium" @click="submit()">提交</el-button>
        <el-button size="medium" @click="close()">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getGPSelect, getGoods, getPacking } from '@/api/product'
import { att, getSon } from '@/api/stock'
import { createAdd } from '@/api/storehouse'
export default {
  name: 'Product',
  props: ['openx', 'title', 'form'],
  data() {
    const self = this
    return {
      loading: false,
      isLoad: false,
      u_number: 0,
      u_box_number: 0,
      list: [], // 托盘数据
      box: [], // 备选的
      selectData: [], // 库位池
      selectPro: [], // 商品池
      checked: true,
      choice: [], // 选中的
      search: '',
      location: [],
      max: 0, // 多选框数量
      // props: {
      //   expandTrigger: 'click',
      //   lazy: true,
      //   lazyLoad (node, resolve) {
      //     if(node.level == 1){
      //       self.getPacking(node.value,resolve)
      //     }else{
      //       resolve([])
      //     }
      //   }
      // },
      options: [
        {
          value: '1',
          label: 'Good'
        },
        {
          value: '2',
          label: 'NG'
        },
        {
          value: '3',
          label: 'Hold'
        }
      ]
    }
  },
  computed: {
    residue() {
      return this.form.num - this.u_number
    },
    list_num() {
      return this.list.length
    }
  },
  watch: {
    list_num() {
      this.max = this.list_num
    }
  },
  created() {
    //this.getLocation(),
    //this.getGoods()
  },
  methods: {
    proChange(list_id, item_id, event) {
      const that = this
      getPacking({ goods_name: event }).then(response => {
        if (response.code === 10000) {
          var data = JSON.parse(JSON.stringify(response.data))
          data.forEach((item) => {
            item.label = item.label
            item.value = item.packing_id + '/' + item.packing_num
          })
          that.list.forEach((item) => {
            if (item.id == list_id) {
              item.products.forEach((it) => {
                if (it.id == item_id) {
                  it.productInfo[1] = ''
                  it.selectPacking = data
                }
              })
            }
          })
        }
      })
    },
    packingChange(list_id, item_id, it_number, event) {
      if (it_number && parseInt(it_number) > 0) {
        //
        var u_number = 0; var u_box_number = 0
        this.list.forEach((item) => {
          if (item.id == list_id) {
            var sum_number = 0; var sum_box_number = 0
            item.products.forEach((it) => {
              var sum = 0
              if (it.id == item_id) {
                var packing_num = parseInt(it.productInfo[1].split('/')[1])
                it.box_number = Math.ceil(parseInt(it.number) / parseInt(packing_num))
              }
              sum_number += it.number ? parseInt(it.number) : 0
              sum_box_number += it.box_number ? parseInt(it.box_number) : 0
            })
            item.number = sum_number
            item.box_number = sum_box_number
          }
          u_number += item.number ? parseInt(item.number) : 0
          u_box_number += item.box_number ? parseInt(item.box_number) : 0
        })
        this.u_number = u_number
        this.u_box_number = u_box_number
      }
    },
    // change(val,event){
    //   this.u_number = 0
    //   this.list.forEach((item)=>{
    //     if(item.id != val){
    //       if(item.number){
    //         this.u_number += parseInt(item.number)
    //       }
    //     }
    //   })
    //   this.list.forEach((item)=>{
    //     if(item.id == val){
    //       if(parseInt(event)>parseInt(this.residue)){
    //         item.number = parseInt(this.residue)
    //         this.u_number += parseInt(this.residue)
    //       }else{
    //         this.u_number += parseInt(event)
    //       }
    //       item.box_number = Math.ceil(parseInt(item.number) / parseInt(this.form.packing_num))
    //     }
    //   })
    // },
    changeNum(list_id, item_id, event) {
      var u_number = 0; var u_box_number = 0
      this.list.forEach((item) => {
        if (item.id == list_id) {
          var sum_number = 0; var sum_box_number = 0
          item.products.forEach((it) => {
            var sum = 0
            if (it.id == item_id) {
              // 判断是否选中商品和规格
              if (!it.productInfo[1]) {
                this.$message({
                  showClose: true,
                  message: '请先选择商品和规格！',
                  type: 'error'
                })
                it.number = ''
              } else {
                var packing_num = parseInt(it.productInfo[1].split('/')[1])
                it.box_number = Math.ceil(parseInt(it.number) / parseInt(packing_num))
              }
            }
            sum_number += it.number ? parseInt(it.number) : 0
            sum_box_number += it.box_number ? parseInt(it.box_number) : 0
          })
          item.number = sum_number
          item.box_number = sum_box_number
        }
        u_number += item.number ? parseInt(item.number) : 0
        u_box_number += item.box_number ? parseInt(item.box_number) : 0
      })
      this.u_number = u_number
      this.u_box_number = u_box_number
      if (this.residue < 0) {
        var u_number = 0
        this.list.forEach((item) => {
          if (item.id == list_id) {
            var sum_number = 0; var sum_box_number = 0
            item.products.forEach((it) => {
              var sum = 0
              if (it.id == item_id) {
                // 判断是否选中商品和规格
                this.$message({
                  showClose: true,
                  message: '超过最大数量！',
                  type: 'error'
                })
                it.number = ''
                it.box_number = ''
              }
              sum_number += it.number ? parseInt(it.number) : 0
              sum_box_number += it.box_number ? parseInt(it.box_number) : 0
            })
            item.number = sum_number
            item.box_number = sum_box_number
          }
          u_number += item.number ? parseInt(item.number) : 0
          u_box_number += item.box_number ? parseInt(item.box_number) : 0
        })
        this.u_number = u_number
        this.u_box_number = u_box_number
      }
    },
    getBox() {
      if (this.location.length == 0) {
        this.$message({
          showClose: true,
          message: '请选择库位！',
          type: 'error'
        })
        return false
      }
      this.loading = true
      const location = JSON.parse(JSON.stringify(this.location))
      if (location.length) {
        const that = this
        getSon({ config_id: location[1], checked: that.checked, search: that.search }).then(response => {
          if (response.code === 10000) {
            that.box = JSON.parse(JSON.stringify(response.data))
            that.loading = false
          }
        })
      }
    },
    /** 初始：查询商品 */
    getGoods() {
      const that = this
      this.isLoad = true
      getGoods().then(response => {
        if (response.code === 10000) {
          that.selectPro = JSON.parse(JSON.stringify(response.data))
          that.selectPro.forEach((item) => {
            item.label = item.goods_name
            item.value = item.goods_name
            this.isLoad = false
          })
        }
      })
    },
    /** 动态获取商品规格 */
    getPacking(val, resolve) {
      const that = this
      getPacking({ goods_name: val }).then(response => {
        if (response.code === 10000) {
          var data = JSON.parse(JSON.stringify(response.data))
          data.forEach((item) => {
            item.label = item.label
            item.value = item.packing_id + '/' + item.packing_num
          })
          resolve(data)
        }
      })
    },
    /** 查询库位 */
    getLocation() {
      const that = this
      att().then(response => {
        if (response.code === 10000) {
          that.selectData = JSON.parse(JSON.stringify(response.data))
          that.selectList(that.selectData)
        }
      })
    },
    /** 处理库位数据 */
    selectList(data) {
      const replaceKey = function(data) {
        data.forEach(function(row, index, arr) {
          const temp = { label: row.name, value: row.config_id }
          if (row.children !== undefined) {
            if (row.children.length > 0) {
              temp['children'] = row.children
            }
            arr[index] = temp
            if (arr[index].children.length > 0) {
              replaceKey(arr[index].children)
            }
          } else {
            arr[index] = temp
          }
        })
      }
      replaceKey(data)
    },
    addList() {
      if (this.residue == 0) {
        this.$message({
          showClose: true,
          message: '没有剩余商品！',
          type: 'error'
        })
      } else {
        var id = new Date().getTime()
        var list = { id: id, tray_id: '', number: '', box_number: '', goods_status: '', products: [] }
        list.products.push({ id: id + 1, selectPro: this.selectPro, selectPacking: [], productInfo: [], panumber: '', box_number: '' })
        this.list.push(list)
        // this.list.push({id:id,tray_id:'',number:'',box_number:'',goods_status:'',products:[]})
        // item.products.push({id:id,selectPro:this.selectPro,selectPacking:[],productInfo:[],panumber:'',box_number:''})
      }
    },
    del(val) {
      this.list = this.list.filter((item) => {
        if (item.id == val) {
          if (item.number) {
            this.u_number -= parseInt(item.number)
            this.u_box_number -= parseInt(item.box_number)
          }
        }
        return item.id != val
      })
    },
    del_son(list_id, item_id) {
      var u_number = 0; var u_box_number = 0
      this.list.forEach((item, index) => {
        if (item.id == list_id) {
          var sum_number = 0; var sum_box_number = 0
          item.products.forEach((it, ind) => {
            var sum = 0
            if (it.id == item_id) {
              item.products.splice(ind, 1)
            } else {
              sum_number += it.number ? parseInt(it.number) : 0
              sum_box_number += it.box_number ? parseInt(it.box_number) : 0
            }
          })
          item.number = sum_number
          item.box_number = sum_box_number
        }
        u_number += item.number ? parseInt(item.number) : 0
        u_box_number += item.box_number ? parseInt(item.box_number) : 0
      })
      this.u_number = u_number
      this.u_box_number = u_box_number
    },
    add(val) {
      var id = new Date().getTime()
      this.list.forEach((item) => {
        if (item.id == val) {
          item.products.push({ id: id, selectPro: this.selectPro, selectPacking: [], productInfo: [], panumber: '', box_number: '' })
        }
      })
    },
    submit() {
      const that = this
      // var arr = []  //收集库位数据
      // for(let i in this.box) {
      //   this.choice.forEach((vo,key)=>{
      //     if(vo == this.box[i].name){
      //       arr[key] = this.box[i].config_id
      //     }
      //   })
      // }

      // this.box.forEach((item,index)=>{
      //   this.choice.forEach((vo,key)=>{
      //     if(vo == item.name){
      //       arr[key] = item.config_id
      //     }
      //   })
      // })
      if (!this.list.length || !this.choice.length) {
        this.$message({
          showClose: true,
          message: '托盘和库位不能为空！',
          type: 'error'
        })
        return false
      } else if (this.list.length != this.choice.length) {
        this.$message({
          showClose: true,
          message: '托盘和库位数量不匹配！',
          type: 'error'
        })
        return false
      }
      var data = {}
      data['choice'] = this.choice
      data['warehousing'] = {
        warehousing_id: this.form.warehousing_id,
        batch_number: this.form.batch_number,
        number: this.u_number,
        box_number: this.u_box_number,
        tray_number: this.choice.length
      }
      var list = []
      var out = 0
      this.list.forEach((item, index) => {
        list[index] = { tray_id: item.tray_id, number: item.number, box_number: item.box_number, goods_status: item.goods_status, products: [] }
        // 判断是否为空托盘
        if (item.products.length == 0) {
          that.$message.warning('空托盘！')
          out = 1
          return false
        }
        item.products.forEach((it, ind) => {
          if (it.productInfo.length != 2 || it.productInfo[0] == '' || it.productInfo[1] == '') {
            that.$message.warning('未选择商品和包装！')
            out = 1
            return false
          }
          list[index]['products'][ind] = { goods_name: it.productInfo[0], packing_id: it.productInfo[1].split('/')[0], number: it.number, box_number: it.box_number }
        })
      })
      data['list'] = list
      data['enter_type'] = 1
      if (out == 1) {
        return false
      }
      createAdd(data).then(response => {
        if (response.code === 10000) {
          that.$message.success(response.message)
          that.$parent.getList()
          that.$emit('update:openx', false)
          // this.$router.push({
          //   path: '/storehouse/tray',
          //   query: { warehousing_id: this.form.warehousing_id, warehousing_son_id: this.form.warehousing_son_id }
          // })
        }
      })
    },
    close() {
      this.$emit('update:openx', false)
    }
  }
}
</script>

<style scoped>
.box-card-left{
  height: 500px;
  overflow-y:auto;
}
.box-card-right{
  height: 500px;
  overflow-y:auto;
}
.area {
  float: left;
  width: 100%;
}

.area p {
  font-size: 14px;
  line-height: 24px;
}

.area .column {
  float: left;
  width: 45%;
  margin-right: 10px;
  margin-bottom: 5px;
}

.area .column .img1{float:left;width:200px;height:40px;margin-left:10px;}

.area .column2 {
  margin-right: 0;
}

.area .zi1 {
  float: left;
  /*border-bottom: 1px solid #fff;*/
  width: 100px;
}

.area .zi2 {
  float: left;
  /*border-bottom: 1px solid #000;*/
  width: 200px;
  margin-left: 10px;
}

i{
  font-size: 25px;
  cursor:pointer;
  margin-top: 25%;
  margin-left: 10%;
}

.box{
  float:left;
  margin: 3px;
  width: 100px;
  display: inline-grid;
}
</style>
